<template>
  <div class="dashboard">
    <div class="welcome-card">
      <el-card>
        <div class="welcome-content">
          <div class="welcome-text">
            <h2>欢迎回来，{{ userStore.userName }}！</h2>
            <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
          </div>
          <div class="welcome-actions">
            <el-button
              type="primary"
              @click="refreshData"
              :loading="loading"
              size="default"
            >
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
            <el-avatar :size="80" :src="userStore.userInfo?.avatar">
              {{ userStore.userName.charAt(0) }}
            </el-avatar>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid" v-loading="loading">
      <el-card v-for="stat in statsData" :key="stat.title" class="stat-card">
        <div class="stat-content">
          <div class="stat-icon" :style="{ backgroundColor: stat.color }">
            <el-icon :size="24">
              <component :is="stat.icon" />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-title">{{ stat.title }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-grid">
      <el-card class="chart-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span class="title">学生就业状态分布</span>
            <div class="chart-actions">
              <el-button
                type="text"
                @click="loadEmploymentStats"
                :loading="loading"
                size="small"
              >
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="employmentChartOption" style="height: 300px;" />
        </div>
      </el-card>

      <el-card class="chart-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span class="title">月度趋势统计</span>
            <div class="chart-actions">
              <el-button
                type="text"
                @click="loadMonthlyTrends"
                :loading="loading"
                size="small"
              >
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="interviewChartOption" style="height: 300px;" />
        </div>
      </el-card>

      <!-- 新增简历状态分布图 -->
      <el-card class="chart-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span class="title">简历状态分布</span>
            <div class="chart-actions">
              <el-button
                type="text"
                @click="loadResumeStats"
                :loading="loading"
                size="small"
              >
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="resumeChartOption" style="height: 300px;" />
        </div>
      </el-card>

      <!-- 新增岗位申请统计图 -->
      <el-card class="chart-card" v-loading="loading">
        <template #header>
          <div class="card-header">
            <span class="title">岗位申请统计</span>
            <div class="chart-actions">
              <el-button
                type="text"
                @click="loadJobStats"
                :loading="loading"
                size="small"
              >
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <v-chart :option="jobApplicationChartOption" style="height: 300px;" />
        </div>
      </el-card>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="title">快捷操作</span>
          </div>
        </template>
        <div class="actions-grid">
          <div
            v-for="action in quickActions"
            :key="action.title"
            class="action-item"
            @click="handleQuickAction(action.path)"
          >
            <div class="action-icon" :style="{ backgroundColor: action.color }">
              <el-icon :size="20">
                <component :is="action.icon" />
              </el-icon>
            </div>
            <div class="action-title">{{ action.title }}</div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import {
  dashboardApi,
  studentDashboardApi,
  teacherDashboardApi,
  adminDashboardApi,
  type DashboardStats,
  type StudentEmploymentStats,
  type InterviewStats,
  type MonthlyTrend
} from '@/api/dashboard'
import { COLORS, CHART_COLORS, STATUS_COLORS, ROLE_COLORS, getChartTheme } from '@/utils/colors'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const dashboardStats = ref<DashboardStats>({
  totalStudents: 0,
  totalResumes: 0,
  totalInterviews: 0,
  totalJobs: 0,
  totalCompanies: 0,
  totalApplications: 0
})
const employmentStats = ref<StudentEmploymentStats>({
  employed: 0,
  unemployed: 0,
  furtherStudy: 0,
  selfEmployed: 0,
  military: 0
})
const interviewTrends = ref<MonthlyTrend[]>([])
const resumeStats = ref({
  draft: 0,
  inProgress: 0,
  submitted: 0,
  approved: 0,
  rejected: 0
})
const jobApplicationStats = ref({
  pending: 0,
  approved: 0,
  rejected: 0,
  total: 0
})

// 学生个人统计数据
const studentPersonalStats = ref({
  resumeCompletion: 0,
  notificationCount: 0
})

// 当前日期
const currentDate = computed(() => formatDate(new Date()))

// 统计数据
const statsData = computed(() => {
  const role = userStore.userInfo?.role
  const stats = dashboardStats.value

  if (role === 'admin') {
    return [
      {
        title: '学生总数',
        value: stats.totalStudents.toLocaleString(),
        icon: 'User',
        color: COLORS.primary
      },
      {
        title: '简历总数',
        value: stats.totalResumes.toLocaleString(),
        icon: 'Document',
        color: COLORS.success
      },
      {
        title: '面试总数',
        value: stats.totalInterviews.toLocaleString(),
        icon: 'ChatDotRound',
        color: COLORS.warning
      },
      {
        title: '岗位总数',
        value: stats.totalJobs.toLocaleString(),
        icon: 'Briefcase',
        color: COLORS.danger
      }
    ]
  } else if (role === 'teacher') {
    return [
      {
        title: '负责学生',
        value: stats.totalStudents.toLocaleString(),
        icon: 'User',
        color: COLORS.primary
      },
      {
        title: '待审简历',
        value: stats.totalResumes.toLocaleString(),
        icon: 'Document',
        color: COLORS.success
      },
      {
        title: '本月面试',
        value: stats.totalInterviews.toLocaleString(),
        icon: 'ChatDotRound',
        color: COLORS.warning
      },
      {
        title: '推荐岗位',
        value: stats.totalJobs.toLocaleString(),
        icon: 'Briefcase',
        color: COLORS.danger
      }
    ]
  } else {
    return [
      {
        title: '简历完成度',
        value: `${studentPersonalStats.value.resumeCompletion}%`,
        icon: 'Document',
        color: COLORS.primary
      },
      {
        title: '面试次数',
        value: stats.totalInterviews.toLocaleString(),
        icon: 'ChatDotRound',
        color: COLORS.success
      },
      {
        title: '申请岗位',
        value: stats.totalApplications.toLocaleString(),
        icon: 'Briefcase',
        color: COLORS.warning
      },
      {
        title: '简历数量',
        value: stats.totalResumes.toLocaleString(),
        icon: 'DocumentCopy',
        color: COLORS.danger
      }
    ]
  }
})

// 快捷操作
const quickActions = computed(() => {
  const role = userStore.userInfo?.role

  if (role === 'admin') {
    return [
      { title: '添加学生', icon: 'UserFilled', color: COLORS.primary, path: '/students/create' },
      { title: '简历管理', icon: 'Document', color: COLORS.success, path: '/resume/management' },
      { title: '发布岗位', icon: 'Plus', color: COLORS.warning, path: '/jobs/create' },
      { title: '系统设置', icon: 'Setting', color: COLORS.info, path: '/system/settings' },
      { title: '查看日志', icon: 'Files', color: COLORS.danger, path: '/system/logs' }
    ]
  } else if (role === 'teacher') {
    return [
      { title: '学生管理', icon: 'User', color: COLORS.primary, path: '/students/list' },
      { title: '简历审核', icon: 'Document', color: COLORS.success, path: '/resume/review' },
      { title: '安排面试', icon: 'ChatDotRound', color: COLORS.warning, path: '/interviews/schedule' },
      { title: '岗位管理', icon: 'Briefcase', color: COLORS.danger, path: '/jobs/list' }
    ]
  } else {
    return [
      { title: '制作简历', icon: 'EditPen', color: COLORS.primary, path: '/resume/create' },
      { title: '面试练习', icon: 'ChatDotRound', color: COLORS.success, path: '/interviews/practice' },
      { title: '浏览岗位', icon: 'Search', color: COLORS.warning, path: '/jobs/list' },
      { title: '个人中心', icon: 'User', color: COLORS.danger, path: '/profile' }
    ]
  }
})

// 就业状态图表配置
const employmentChartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '就业状态',
      type: 'pie',
      radius: '50%',
      data: [
        { value: employmentStats.value.employed, name: '已就业' },
        { value: employmentStats.value.unemployed, name: '未就业' },
        { value: employmentStats.value.furtherStudy, name: '继续深造' },
        { value: employmentStats.value.selfEmployed, name: '自主创业' },
        { value: employmentStats.value.military, name: '参军入伍' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

// 面试统计图表配置
const interviewChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: CHART_COLORS.tooltipBg
      }
    }
  },
  legend: {
    data: ['面试安排', '面试完成', '申请数量', '通过申请']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: interviewTrends.value.map(item => item.month)
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '面试安排',
      type: 'line',
      smooth: true,
      data: interviewTrends.value.map(item => item.interviews),
      itemStyle: {
        color: COLORS.primary
      }
    },
    {
      name: '面试完成',
      type: 'line',
      smooth: true,
      data: interviewTrends.value.map(item => item.completedInterviews),
      itemStyle: {
        color: COLORS.success
      }
    },
    {
      name: '申请数量',
      type: 'line',
      smooth: true,
      data: interviewTrends.value.map(item => item.applications),
      itemStyle: {
        color: COLORS.warning
      }
    },
    {
      name: '通过申请',
      type: 'line',
      smooth: true,
      data: interviewTrends.value.map(item => item.approvedApplications),
      itemStyle: {
        color: COLORS.danger
      }
    }
  ]
}))

// 简历状态图表配置
const resumeChartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '简历状态',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      data: [
        { value: resumeStats.value.draft, name: '草稿' },
        { value: resumeStats.value.inProgress, name: '进行中' },
        { value: resumeStats.value.submitted, name: '已提交' },
        { value: resumeStats.value.approved, name: '已通过' },
        { value: resumeStats.value.rejected, name: '已拒绝' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: false,
        position: 'center'
      },
      labelLine: {
        show: false
      }
    }
  ]
}))

// 岗位申请统计图表配置
const jobApplicationChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['待审核', '已通过', '已拒绝', '总申请']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '申请数量',
      type: 'bar',
      data: [
        {
          value: jobApplicationStats.value.pending,
          itemStyle: { color: COLORS.warning }
        },
        {
          value: jobApplicationStats.value.approved,
          itemStyle: { color: COLORS.success }
        },
        {
          value: jobApplicationStats.value.rejected,
          itemStyle: { color: COLORS.danger }
        },
        {
          value: jobApplicationStats.value.total,
          itemStyle: { color: COLORS.primary }
        }
      ],
      barWidth: '60%'
    }
  ]
}))

// 处理快捷操作
const handleQuickAction = (path: string) => {
  router.push(path)
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    await loadDashboardData()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  loading.value = true
  try {
    const role = userStore.userInfo?.role

    // 根据角色加载不同的数据
    if (role === 'admin') {
      await loadAdminDashboard()
    } else if (role === 'teacher') {
      await loadTeacherDashboard()
    } else {
      await loadStudentDashboard()
    }

    // 加载通用数据
    await Promise.all([
      loadEmploymentStats(),
      loadMonthlyTrends(),
      loadResumeStats(),
      loadJobStats()
    ])

  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载仪表盘数据失败')
  } finally {
    loading.value = false
  }
}

// 加载管理员仪表盘数据
const loadAdminDashboard = async () => {
  try {
    const [overviewRes, systemRes] = await Promise.all([
      dashboardApi.getOverviewStats(),
      adminDashboardApi.getSystemOverview()
    ])

    console.log('管理员概览数据:', overviewRes.data)
    console.log('系统概览数据:', systemRes.data)

    // 确保数据结构正确
    dashboardStats.value = {
      totalStudents: overviewRes.data?.total_students || 0,
      totalResumes: overviewRes.data?.total_resumes || 0,
      totalInterviews: overviewRes.data?.total_interviews || 0,
      totalJobs: overviewRes.data?.total_jobs || 0,
      totalCompanies: overviewRes.data?.total_companies || 0,
      totalApplications: overviewRes.data?.total_applications || 0
    }
  } catch (error) {
    console.error('加载管理员数据失败:', error)
    ElMessage.error('加载管理员数据失败')
  }
}

// 加载教师仪表盘数据
const loadTeacherDashboard = async () => {
  try {
    const [statsRes, studentsRes] = await Promise.all([
      dashboardApi.getOverviewStats(),
      teacherDashboardApi.getMyStudentsStats()
    ])

    console.log('教师概览数据:', statsRes.data)
    console.log('教师学生数据:', studentsRes.data)

    // 结合全局统计和个人负责的学生统计
    dashboardStats.value = {
      totalStudents: studentsRes.data?.total_students || 0, // 使用负责的学生数
      totalResumes: studentsRes.data?.resume_stats?.total || 0,
      totalInterviews: studentsRes.data?.interview_stats?.total || 0,
      totalJobs: statsRes.data?.total_jobs || 0, // 使用全局岗位数
      totalCompanies: statsRes.data?.total_companies || 0,
      totalApplications: statsRes.data?.total_applications || 0
    }
  } catch (error) {
    console.error('加载教师数据失败:', error)
    ElMessage.error('加载教师数据失败')
  }
}

// 加载学生仪表盘数据
const loadStudentDashboard = async () => {
  try {
    const [personalRes, progressRes] = await Promise.all([
      studentDashboardApi.getPersonalStats(),
      studentDashboardApi.getResumeProgress()
    ])

    console.log('学生个人数据:', personalRes.data)
    console.log('学生简历进度:', progressRes.data)

    // 处理学生个人数据
    dashboardStats.value = {
      totalStudents: 1, // 学生只看自己
      totalResumes: personalRes.data?.resumeCount || 0,
      totalInterviews: personalRes.data?.interviewCount || 0,
      totalJobs: 0, // 学生不显示总岗位数，显示申请数
      totalCompanies: 0,
      totalApplications: personalRes.data?.applicationCount || 0
    }

    // 更新学生个人统计
    studentPersonalStats.value = {
      resumeCompletion: Math.round(personalRes.data?.resumeCompletion || 0),
      notificationCount: 0 // 暂时设为0，后续可以从通知API获取
    }
  } catch (error) {
    console.error('加载学生数据失败:', error)
    ElMessage.error('加载学生数据失败')
  }
}

// 加载就业统计数据
const loadEmploymentStats = async () => {
  try {
    const response = await dashboardApi.getStudentEmploymentStats()
    console.log('就业统计数据:', response.data)

    // 确保数据结构正确
    employmentStats.value = {
      employed: response.data?.employed || 0,
      unemployed: response.data?.unemployed || 0,
      furtherStudy: response.data?.further_study || 0,
      selfEmployed: response.data?.self_employed || 0,
      military: response.data?.military || 0
    }
  } catch (error) {
    console.error('加载就业统计失败:', error)
    ElMessage.error('加载就业统计失败')
    // 使用默认数据
    employmentStats.value = {
      employed: 0,
      unemployed: 0,
      furtherStudy: 0,
      selfEmployed: 0,
      military: 0
    }
  }
}

// 加载月度趋势数据
const loadMonthlyTrends = async () => {
  try {
    const response = await dashboardApi.getMonthlyTrends({ months: 6 })
    console.log('月度趋势数据:', response.data)

    // 确保数据是数组格式
    if (Array.isArray(response.data)) {
      interviewTrends.value = response.data.map(item => ({
        month: item.month || '',
        interviews: item.interviews || 0,
        completedInterviews: item.completed_interviews || 0,
        applications: item.applications || 0,
        approvedApplications: item.approved_applications || 0
      }))
    } else {
      interviewTrends.value = []
    }
  } catch (error) {
    console.error('加载趋势数据失败:', error)
    ElMessage.error('加载趋势数据失败')
    // 使用默认数据
    interviewTrends.value = [
      { month: '1月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 },
      { month: '2月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 },
      { month: '3月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 },
      { month: '4月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 },
      { month: '5月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 },
      { month: '6月', interviews: 0, completedInterviews: 0, applications: 0, approvedApplications: 0 }
    ]
  }
}

// 加载简历统计数据
const loadResumeStats = async () => {
  try {
    const response = await dashboardApi.getResumeStats()
    console.log('简历统计数据:', response.data)

    // 确保数据结构正确，处理后端字段名
    resumeStats.value = {
      draft: response.data?.draft || 0,
      inProgress: response.data?.in_progress || 0,
      submitted: response.data?.pending_review || 0, // 待审核作为已提交
      approved: response.data?.approved || 0,
      rejected: response.data?.rejected || response.data?.needs_revision || 0
    }
  } catch (error) {
    console.error('加载简历统计失败:', error)
    ElMessage.error('加载简历统计失败')
    // 使用默认数据
    resumeStats.value = {
      draft: 0,
      inProgress: 0,
      submitted: 0,
      approved: 0,
      rejected: 0
    }
  }
}

// 加载岗位申请统计数据
const loadJobStats = async () => {
  try {
    const response = await dashboardApi.getJobStats()
    console.log('岗位统计数据:', response.data)

    // 确保数据结构正确
    jobApplicationStats.value = {
      pending: response.data?.applications?.pending || 0,
      approved: response.data?.applications?.approved || 0,
      rejected: response.data?.applications?.rejected || 0,
      total: response.data?.applications?.total || 0
    }
  } catch (error) {
    console.error('加载岗位统计失败:', error)
    ElMessage.error('加载岗位统计失败')
    // 使用默认数据
    jobApplicationStats.value = {
      pending: 0,
      approved: 0,
      rejected: 0,
      total: 0
    }
  }
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style lang="scss" scoped>
.dashboard {
  .welcome-card {
    margin-bottom: 24px;
    
    .welcome-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .welcome-text {
        h2 {
          margin: 0 0 8px 0;
          color: var(--text-color-primary);
          font-weight: 600;
        }

        p {
          margin: 0;
          color: var(--text-color-secondary);
        }
      }

      .welcome-actions {
        display: flex;
        align-items: center;
        gap: 16px;
      }
    }
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 24px;
    margin-bottom: 24px;
    
    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          margin-right: 16px;
        }
        
        .stat-info {
          .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: var(--text-color-primary);
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-title {
            font-size: 14px;
            color: var(--text-color-secondary);
          }
        }
      }
    }
  }
  
  .charts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 24px;
    margin-bottom: 24px;
    
    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-weight: 600;
          color: var(--text-color-primary);
        }
      }

      .chart-container {
        height: 300px;
      }
    }
  }
  
  .quick-actions {
    .actions-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 16px;
      
      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20px;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background-color: var(--fill-color-light);
          transform: translateY(-2px);
        }
        
        .action-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          margin-bottom: 12px;
        }
        
        .action-title {
          font-size: 14px;
          color: var(--text-color-primary);
          text-align: center;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard {
    .welcome-card {
      .welcome-content {
        flex-direction: column;
        text-align: center;
        gap: 16px;
      }
    }
    
    .stats-grid {
      grid-template-columns: 1fr;
    }
    
    .charts-grid {
      grid-template-columns: 1fr;
    }
    
    .quick-actions {
      .actions-grid {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}
</style>
